package ex55.mm.flow.impound.quote.common.kit;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.EnumUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * _ 开始的为可以容错的
 * 正常的是不容错的
 */
public class CastKit {
    public static <E extends Enum<E>> E _enums(final Class<E> enumClass, final String enumName) {
        return EnumUtils.getEnum(enumClass, enumName);
    }

    public static Date _date(Timestamp timestamp) {
        return timestamp;
    }

    public static String string(Object o) {
        Assert.notNull(o, "cast body to string NPE");
        return o.toString();
    }

    public static String _string(Object o) {
        if (o == null) {
            return null;
        }
        return o.toString();
    }

    public static Timestamp timestamp(Date date) {
        Assert.notNull(date, "cast body to Timestamp NPE");
        return new Timestamp(date.getTime());
    }

    public static Timestamp _timestamp(Date date) {
        return date == null ? null : new Timestamp(date.getTime());
    }

    public static String stringUTCISO8601(Date date) {
        return DateTimeKit.stringUTCISO8601(date);
    }

    public static String stringOf(Object object) {
        if (object == null) {
            return "null";
        }
        if (object instanceof BigDecimal) {
            return ((BigDecimal) object).stripTrailingZeros().toPlainString();
        } else if (object instanceof Date) {
            return stringUTCISO8601((Date) object);
        } else if (object instanceof DateTime) {
            return ((DateTime) object).withZone(DateTimeZone.UTC).toString(ISODateTimeFormat.dateTime());
        } else if (object.getClass().isArray()) {
            return ArrayUtils.toString(object);
        }
        return String.valueOf(object);
    }


    public static <T> List<T> _jsonList(String json, Class<T> clazz) {
        if (!StringUtils.hasText(json)) {
            return null;
        }
        try {
            return JsonKit.parseList(json, clazz);
        } catch (Exception ignored) {
        }
        return null;
    }
}
